package com.cty.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

/**
 * ProducerQuickStart
 *
 * @author tianyuchan
 * @since 2024/7/10
 */

public class ProducerQuickStart {

    public static void main(String[] args) {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"101.42.44.206:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

        //封装发送的消息
        ProducerRecord<String,String> kvProducerRecord = new ProducerRecord<String, String>("itheima-topic","100001","hello kafka");

        //3.发送消息
//        producer.send(kvProducerRecord);

        // 同步发送消息（阻塞等待MQ响应偏移量，效率低）
//        try {
//            RecordMetadata recordMetadata = producer.send(kvProducerRecord).get();
//            System.out.println(recordMetadata.offset());
//        } catch (InterruptedException | ExecutionException e) {
//            System.out.println("记录异常信息到日志表中");
//            throw new RuntimeException(e);
//        }

        // 异步发送消息（通过回调函数接收MQ响应偏移量和捕获异常）
        producer.send(kvProducerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e != null){
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println(recordMetadata.offset());
            }
        });

        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

}
